import json
import logging
import requests
from bs4 import BeautifulSoup

from wu.seal.emailtool.Utils import Utils

__logger = logging.getLogger("config_set_helper")
__logger.setLevel(logging.DEBUG)
logging.basicConfig(level=logging.DEBUG)


def st_2_ict(st: str):
    dc = {}
    for line in st.splitlines():
        key = line.split(":")[0].strip()
        value = line.split(":")[1].strip()
        dc[key] = value
    return dc


def cost_2_dict(st: str):
    dc = {}
    for line in st.split(";"):
        key = line.split("=")[0].strip()
        value = line.split("=")[1].strip()
        dc[key] = value
    return dc


def set_web_tool_app_see_config(roll_out_rate: str, branch_name: str):
    '''根据roll out比例自动设置app see web tool 后台配置'''
    utils = Utils()
    if utils.getAppName(branch_name) is "TalkU":
        #只有TalkU才有App See 开关配置
        open_rate = roll_out_rate.split('->')[-1]
        open_rate_int = int(open_rate.replace("%", ""))
        if open_rate_int <= 2:
            __logger.info("当前开放比例小于等2%，所以开启appsee")
            __set_app_see_config_on_web_tool(utils.getAppVersion(branch_name), True)
        else:
            __logger.info("当前开放比例大于2%，所以关闭appsee")
            __set_app_see_config_on_web_tool(utils.getAppVersion(branch_name), False)


def __set_app_see_config_on_web_tool(app_version: str, open: bool):
    '''给指定的版本的TalkU APP 打开或关闭APP see'''
    session = requests.session()

    login_url = "http://54.153.32.33:8080/webtool/user/login"

    login_info = {"userName": "jarvis.cai@dingtone.me",
                  "password": 12345678}

    if session.post(login_url, params=login_info).status_code == 200:
        __logger.info("登录webtool成功")
    else:
        raise Exception("登录webtool失败！")

    url = "http://54.153.32.33:8080/webtool/cfg/pn1/ConfigMngrInput"

    data = {"paramString": "1--Config.dttalk2.appCommonConfig"}
    read_config_html = session.post(url, data=data).text
    bfs = BeautifulSoup(read_config_html, "html.parser")
    read_config_json = bfs.findAll('textarea', attrs={"readonly": "readonly", 'rows': '3'})[0].get_text()
    config = json.loads(read_config_json)
    version_config = config['appSeeApplyVersion']
    if open:
        if version_config == app_version:
            __logger.info("当前当前状态已经是相应版本的配置开启状态，无需再次设置配置")
            return
        config['appSeeApplyVersion'] = app_version
    else:
        if version_config == "":
            __logger.info("当前状态已经是相应版本的关闭配置状态，无需再次设置配置")
            return
        config['appSeeApplyVersion'] = ""

    write_config_json = json.dumps(config)

    update_config_url = "http://54.153.32.33:8080/webtool/cfg/pn1/configAddOrUpdate"
    data = {"cfg_Const": 1, "cfg_Key": "Config.dttalk2.appCommonConfig",
            "cfg_Value": write_config_json, "whichValues": 1, "inputOfficeNum": 906}
    if session.post(update_config_url, data=data).status_code == 200:
        __logger.info("配置内容修改成功！")
    else:
        raise Exception("配置内容修改失败！")
    config_plus_version_code_url = "http://54.153.32.33:8080/webtool/version/pn1/versioncode_config"

    if session.get(config_plus_version_code_url).status_code == 200:
        __logger.info("版本号加1成功！")
    else:
        raise Exception("版本号加1失败！")

    reload_config_url = "http://54.153.32.33:8080/webtool/cfg/common/reload/pn1/dt_glb/gwebsvr"
    get = session.get(reload_config_url)
    if get.status_code == 200 and get.text.lower().count("error") <= 1:
        __logger.info("配置reload成功！")
    else:
        raise Exception("配置reload失败！")

    if open:
        __logger.info("请打开AppSee平台的配置开关：https://dashboard.appsee.com/home/talku-for-ios-android-pn#/settings/index#android/all/month/all")

    else:
        __logger.info("请关闭AppSee平台的配置开关：https://dashboard.appsee.com/home/talku-for-ios-android-pn#/settings/index#android/all/month/all")



def __set_app_see_config_on_app_see_web(app_version: str, open: bool):
    '''爬虫式方式实现开关app see网站上的配置开关，不过现在还没有实现'''
    app_see_login_url = "https://dashboard.appsee.com/login"
    params = {"Email": "seal.wu@dingtone.me",
              "Password": "kgduitee123"}
    session = requests.session()
    print(session.post(app_see_login_url, params=params).text)
    get = session.get("https://dashboard.appsee.com/home")
    print(session.get("https://dashboard.appsee.com/home/testapp-test#/settings/index#ios/none/month/none").text)
    __aft = get.headers['_aft']
    cookie = get.cookies
    print(requests.utils.dict_from_cookiejar(cookie))
    headers = {
        'origin': "https://dashboard.appsee.com",
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "zh-CN,zh;q=0.9",
        'user-agent': "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36",
        'content-type': "application/json; charset=UTF-8",
        'accept': "*/*",
        'referer': "https://dashboard.appsee.com/home/testapp-test",
        'x-requested-with': "XMLHttpRequest",
        'connection': "keep-alive",
        'cache-control': "no-cache",
        '_aft': "uLa2Gk3J5k5Ro_vQ-paEl08AC-KFKzpTSRcWJv-LSqwdh2Le2G1DG1-guDFvMRXjo8E7r5fKaLk34VOa9--sZVICkTFxpdhwK9kr09fknVgpAldK0",
    }
    cookie = requests.utils.cookiejar_from_dict(cost_2_dict(
        """appsee-lp=http://www.appsee.com/; _ga=GA1.2.1174340546.1541760661; userlanguage=zh-CN; wooTracker=nCN6q3PEpm2B; appsee-referral=https://dashboard.appsee.com/home/coverme; __qca=P0-1884901870-1544761861356; trd_cid=15447620522032020; trd_first_visit=1544762053; trd_exitintentclient=1544762052518517; __utmz=119577432.1544762080.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _aftc=EKE9vBJ-EEb6wRM0mS_TwbmMJCtM75uUBx2E-WuU3dv6CYCh7wJzqPE66tgQbFAkLe4AFWaKGSSI5mwrcbrF7gPNvL01; timezoneoffset=480; first_session_entrance=false; collapsible=; _gcl_au=1.1.486251857.1547103463; Hm_lvt_17cd0f12460ed55573a7ad9c3b7b421f=1544761859,1547103466; __utma=119577432.1174340546.1541760661.1544762080.1547103636.2; __utmc=119577432; trd_pw=12; trd_pws=8; trd_taskrestricted=null-1547103514%7Cnull-1547103652%7Cnull-1547103836; ASP.NET_SessionId=bejftnfpjxxefgzlavcqhgba; _gid=GA1.2.95777731.1547196514; Hm_lpvt_17cd0f12460ed55573a7ad9c3b7b421f=1547196514; _fbp=fb.1.1547196517325.421393091; .ASPXAUTH=C76E5EA1B928E7D82A67A3642242592374075C301B2819B28904894229B7F61ACF252110930860FFE70FC2D6865437D99A3802F6789B9BFF9DC26D98EA3E47ED94FEB289E77AF98CCF7BA7F1E02492E080835DBEF727609040159577E51C4BA7D74AA6A955AA7CE018E60248E3B0767267DE834F; __adroll_fpc=bbb751d957f1edb8b58c01f26a370dfe; __ar_v4=%7CTOFCF2RF2JDAVKHNWNUELX%3A20190110%3A1%7CVFS2SP26LRCRJEPJBJSLJF%3A20190110%3A1%7C56TUAKZZRNCO5ECDQMFGF7%3A20190110%3A1; last_selected_app_name=testapp-test"""))

    payload = "{\"Id\":\"5c385917b9e4f814745ca9ad\",\"VideoRecordingQuality\":\"Medium\",\"MaxDailyVideos\":null,\"MaxVideoLength\":\"600\",\"SensitiveDataPolicy\":\"HideAll\",\"platform\":\"ios\",\"VideoRecordingRatio\":0.1,\"MetadataRecordingRatio\":null,\"HiddenScreenIds\":null,\"WhitelistScreenIds\":null,\"conditionsData\":[{\"RecordAll\":false,\"UploadPolicy\":0,\"Countries\":null,\"DeviceNames\":null,\"OSVersions\":null,\"AppVersions\":null,\"Screens\":null,\"Events\":null,\"FromSession\":null,\"ToSession\":null,\"CrashesOnly\":null,\"AppUserIds\":null,\"Id\":\"5c385917b9e4f814745ca9ab\"}]}"
    web_setting_update_url = "https://dashboard.appsee.com/settings/updatesettings"
    print(session.post(web_setting_update_url, headers=headers, data=payload, cookies=cookie).text)


def __test_all():
    headers = {
        'origin': "https://dashboard.appsee.com",
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "zh-CN,zh;q=0.9",
        'user-agent': "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36",
        'content-type': "application/json; charset=UTF-8",
        'accept': "*/*",
        'referer': "https://dashboard.appsee.com/home/testapp-test",
        'x-requested-with': "XMLHttpRequest",
        'connection': "keep-alive",
        '_aft': "uLa2Gk3J5k5Ro_vQ-paEl08AC-KFKzpTSRcWJv-LSqwdh2Le2G1DG1-guDFvMRXjo8E7r5fKaLk34VOa9--sZVICkTFxpdhwK9kr09fknVgpAldK0",
        'cache-control': "no-cache",
        'postman-token': "89e019b8-7469-9726-04a4-ab74705ed860"
    }

    cookie = requests.utils.cookiejar_from_dict(cost_2_dict(
        """appsee-lp=http://www.appsee.com/; _ga=GA1.2.1174340546.1541760661; userlanguage=zh-CN; wooTracker=nCN6q3PEpm2B; appsee-referral=https://dashboard.appsee.com/home/coverme; __qca=P0-1884901870-1544761861356; trd_cid=15447620522032020; trd_first_visit=1544762053; trd_exitintentclient=1544762052518517; __utmz=119577432.1544762080.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _aftc=EKE9vBJ-EEb6wRM0mS_TwbmMJCtM75uUBx2E-WuU3dv6CYCh7wJzqPE66tgQbFAkLe4AFWaKGSSI5mwrcbrF7gPNvL01; timezoneoffset=480; first_session_entrance=false; collapsible=; _gcl_au=1.1.486251857.1547103463; Hm_lvt_17cd0f12460ed55573a7ad9c3b7b421f=1544761859,1547103466; __utma=119577432.1174340546.1541760661.1544762080.1547103636.2; __utmc=119577432; trd_pw=12; trd_pws=8; trd_taskrestricted=null-1547103514%7Cnull-1547103652%7Cnull-1547103836; ASP.NET_SessionId=bejftnfpjxxefgzlavcqhgba; _gid=GA1.2.95777731.1547196514; Hm_lpvt_17cd0f12460ed55573a7ad9c3b7b421f=1547196514; _fbp=fb.1.1547196517325.421393091; .ASPXAUTH=C76E5EA1B928E7D82A67A3642242592374075C301B2819B28904894229B7F61ACF252110930860FFE70FC2D6865437D99A3802F6789B9BFF9DC26D98EA3E47ED94FEB289E77AF98CCF7BA7F1E02492E080835DBEF727609040159577E51C4BA7D74AA6A955AA7CE018E60248E3B0767267DE834F; __adroll_fpc=bbb751d957f1edb8b58c01f26a370dfe; __ar_v4=%7CTOFCF2RF2JDAVKHNWNUELX%3A20190110%3A1%7CVFS2SP26LRCRJEPJBJSLJF%3A20190110%3A1%7C56TUAKZZRNCO5ECDQMFGF7%3A20190110%3A1; last_selected_app_name=testapp-test"""))
    url = "https://dashboard.appsee.com/settings/updatesettings"

    payload = "{\"Id\":\"5c385917b9e4f814745ca9ad\",\"VideoRecordingQuality\":\"Medium\",\"MaxDailyVideos\":null,\"MaxVideoLength\":\"600\",\"SensitiveDataPolicy\":\"HideAll\",\"platform\":\"ios\",\"VideoRecordingRatio\":0.1,\"MetadataRecordingRatio\":null,\"HiddenScreenIds\":null,\"WhitelistScreenIds\":null,\"conditionsData\":[{\"RecordAll\":false,\"UploadPolicy\":0,\"Countries\":null,\"DeviceNames\":null,\"OSVersions\":null,\"AppVersions\":null,\"Screens\":null,\"Events\":null,\"FromSession\":null,\"ToSession\":null,\"CrashesOnly\":null,\"AppUserIds\":null,\"Id\":\"5c385917b9e4f814745ca9ab\"}]}"
    post = requests.post(url, data=payload, headers=headers, cookies=cookie)
    print(post.text)
